package top.qrcodepay.plugin;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.DocumentBuilderFactory;

import org.black_ixx.playerpoints.PlayerPoints;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class ServiceRequester {
	
	public static int checkServerNumber(String appNumber){
		if (!"YourID".equals(appNumber)) {
			String result = getResponse("/plugin/check?number=" + appNumber);
			if (result != null) return Integer.valueOf(result);
			else return 0;
		} else {
			return 0;
		}
	}
	
	static Runnable runnable = new Runnable() {
		@Override
		public void run() {
			if (QrcodePay.checked) heartbeatExcutor(QrcodePay.appNumber);
			heatbeat();
		}
	};
	
	public static void heatbeat() {
		Bukkit.getScheduler().scheduleSyncDelayedTask(QrcodePay.getPlugin(QrcodePay.class), runnable, 100);
	}
	
	public static void heartbeatExcutor(String appNumber) {
		String result = getResponse("/plugin/heartbeat?number=" + appNumber);
		if (result != null) {
			result = result.replaceFirst("^\"", "").replaceFirst("\"$", "");
			if (!"".equals(result)) {
				InputSource source = new InputSource(new StringReader(result));
				Document document = null;
				try {
					document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(source);
				} catch (Exception e) {
					e.printStackTrace();
				}
				Element element = document.getDocumentElement();
				NodeList nodeList = element.getChildNodes(); 
				for (int i = 0; i < nodeList.getLength(); i++) {
					Node node = nodeList.item(i);
					String id = "", name = "", amount = "";
					NodeList childList = node.getChildNodes();
					for (int j = 0; j < childList.getLength(); j++) {
						Node childNode = childList.item(j);
						if ("id".equals(childNode.getNodeName())) {
							id = childNode.getTextContent();
						} else if ("name".equals(childNode.getNodeName())) {
							name = childNode.getTextContent();
						} else if ("amount".equals(childNode.getNodeName())) {
							amount = childNode.getTextContent();
						}
					}
					boolean status = false;
					Player player = Bukkit.getServer().getPlayer(name);
					if (player != null && player.isOnline()) {
						player.sendMessage("§6§l[QrcodePay] 您充值的 " + amount + " 点券已到账！");
						JavaPlugin.getPlugin(PlayerPoints.class).getAPI().give(player.getUniqueId(),Integer.valueOf(amount));
						status = true;
					}
					getResponse("/plugin/confirm?id=" + id + "&number=" + appNumber + "&status=" + status);
				}
			}
		}
	}
	
	public static String getResponse(String link) {
		StringBuffer sb = new StringBuffer();
		try {
			URL url = new URL("http://qrcodepay.top" + link);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestProperty("Content-Type", "text/html");
			connection.setConnectTimeout(500);
			connection.setReadTimeout(1000);
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line; 
			while ((line = in.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {
			return null;
		}
		return sb.toString();
	}
	
}
